import { AutoComplete, Card, Empty, Form, Input, Table } from 'antd';
import { useContext, useMemo, useState } from 'react';
import { PurchaseSupplierStatisticsContext } from '../common';
import { SearchOutlined } from '@ant-design/icons';
import { supplierTableColumns } from '../mconfig';
import { commonPageSizeOptions, showTotalInfo } from '@/common/constVariable';
import _ from 'lodash';
import moment from 'moment';
import { SupplierManageServices } from '../services';
import { history } from 'umi';

const StatisticsManageViewBottom = ({ searchParams }) => {
  /**
   * 解构上下文
   * */
  const { curRes, styleFixCls, statisticsData, reloadRequest } = useContext(PurchaseSupplierStatisticsContext);

  /**
   * 表单Ref
   * */
  const [searchForm] = Form.useForm();

  /**
   * 保存搜索参数
   * */
  const [searchValue, setSearchValue] = useState<string>('');

  /**
   * 保存分页参数
   * */
  const [pageSizeObj, setPageSizeObj] = useState<any>({
    page: 1,
    rows: 10,
  });

  /**
   * 请求供应商
   * */
  const { supplierData } = SupplierManageServices(curRes);

  /**
   * 切换分页
   * */
  const handlePaginationChange = (current: number, pageSize: number) => {
    reloadRequest({ page: current, pageSize });
    setPageSizeObj({
      page: current,
      rows: pageSize,
    });
  };

  /**
   * 下拉选择内容
   * */
  const supplierListMemo = useMemo(() => {
    let returnData: Record<string, any>[] = [];
    if (searchValue && supplierData?.length > 0) {
      supplierData?.forEach((item) => {
        if (item?.fullName?.includes(searchValue)) {
          returnData?.push({
            value: item?.fullName,
            label: item?.fullName,
            key: item?.id,
          });
        }
      });
    }
    return returnData;
  }, [searchValue, supplierData]);

  /**
   * 搜索方法
   * */
  const onSearchFun = () => {
    const searchValue = searchForm?.getFieldValue('supplierName');
    const supplierObj = supplierData?.find((item) => item?.fullName === searchValue);
    const params = {
      supplierName: searchValue,
      supplierID: supplierObj?.id || null,
      ...searchParams,
    };
    let [stateTime, endTime] = params?.timeRanges;
    stateTime = moment(stateTime)?.format('YYYY-MM-DD 00:00:00');
    endTime = moment(endTime)?.format('YYYY-MM-DD 23:59:59');
    params.stateTime = stateTime;
    params.endTime = endTime;

    delete params?.['timeRanges'];

    // 接口
    reloadRequest({ ...params });
  };

  /**
   * 点击供应商名字跳转详情
   * */
  const onClickSupplierName = (record) => {
    history.push({
      pathname: `/sourceController/manage`,
      state: {
        statistics_sourceIds: record?.sourceIds,
        // delRouterNameSource: history.location.pathname, //必传,要删除的路由名称
      },
    });
  };

  return (
    <div className={styleFixCls + 'CenterBox'}>
      <Card
        className={styleFixCls + 'CenterBox-TableCardBox'}
        title={
          <div>
            <Form form={searchForm}>
              <Form.Item name="supplierName">
                <AutoComplete
                  options={supplierListMemo}
                  value={searchValue}
                  notFoundContent={<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
                  onSelect={(value, option) => {
                    searchForm?.setFieldsValue({ supplierID: option?.key });
                    setSearchValue(value);
                  }}
                  onDropdownVisibleChange={(open) => {
                    if (!open) {
                      onSearchFun();
                    }
                  }}
                >
                  <Input
                    suffix={<SearchOutlined />}
                    onChange={(e) => {
                      setSearchValue(e?.target?.value);
                    }}
                    placeholder="请按供应商名称搜索"
                    allowClear={true}
                  />
                </AutoComplete>
              </Form.Item>
              <Form.Item name={'supplierID'} style={{ display: 'none' }}>
                <Input hidden />
              </Form.Item>
            </Form>
          </div>
        }
      >
        <div className="list-table">
          <Table
            size="small"
            bordered={true}
            columns={supplierTableColumns(onClickSupplierName)}
            dataSource={statisticsData}
            rowKey={(node) => node?.sourceIds}
            pagination={{
              showQuickJumper: true,
              showSizeChanger: true,
              pageSizeOptions: commonPageSizeOptions,
              showTotal: showTotalInfo,
              onChange: handlePaginationChange,
              pageSize: pageSizeObj?.rows,
              current: pageSizeObj?.page,
              total: statisticsData?.length,
            }}
          />
        </div>
      </Card>
    </div>
  );
};

export { StatisticsManageViewBottom };
